<template>
  <div>
    <!-- 导航面包屑 -->
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>光伏设备</a-breadcrumb-item>
      <a-breadcrumb-item>设备列表</a-breadcrumb-item>
    </a-breadcrumb>

    <a-card>
      <!-- 顶部标签页 -->
      <a-tabs v-model:active-key="tabsActiveKey" @change="handleTabsChange">
        <a-tab-pane v-for="(item, index) in tabsList" :key="item.value" :title="item.key" />
      </a-tabs>

      <!-- 设备表格 -->
      <a-table
          :loading="loading"
          ref="tableRef"
          row-key="id"
          v-bind:hide-expand-button-on-empty="true"
          :pagination="false"
          :bordered="{ wrapper: true, cell: true }"
          :columns="columns"
          :data="renderData"
      >
        <!-- 设备名称 -->
        <template #deviceName="{ record }">
          <a-tag style="color: rgb(var(--primary-6))" checkable>
            <template #icon>
              <icon-storage v-if="record.isGroup == 1" style="color: rgb(var(--primary-6))" />
              <icon-thunderbolt v-else style="color: rgb(var(--primary-6))" />
            </template>
            {{ record.deviceName }}
          </a-tag>
        </template>

        <!-- 组件容量 kWp -->
        <template #ratedVolume="{ record }">
          <div v-if="record.isGroup == 0">{{ record.ratedVolume }}kWp</div>
        </template>

        <!-- 发电功率 kW -->
        <template #electricPower="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.electricPower }}kW</div>
        </template>

        <!-- 当日发电量 kWh -->
        <template #electricQuantity="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.electricQuantity }}kWh</div>
        </template>

        <!-- 当日满发电小时 -->
        <template #electricHours="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.electricHours || '0' }}</div>
        </template>

        <!-- 直流离散率 -->
        <template #dcDispersionRate="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.dcDispersionRate || '0' }}%</div>
        </template>

        <!-- 功率归一化 -->
        <template #normalizedRate="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.normalizedRate || '0' }}%</div>
        </template>

        <!-- 数据更新时间 -->
        <template #staticTime="{ record }">
          <div v-if="record.isGroup == 0">{{ record.deviceDayRuntime.staticTime || '-' }}</div>
        </template>

        <!-- 状态 -->
        <template #stopFlag="{ record }">
          <div v-if="record.isGroup == 0">
            <stop-flag :value="record.stopFlag" />
          </div>
        </template>

        <!-- 操作 -->
        <template #operate="{ record }">
          <a-button
              v-if="record.isGroup == 0"
              size="small"
              type="text"
              :status="record.stopFlag == 1 ? 'normal' : 'warning'"
              @click="handleStopFlag(record)"
          >
            {{ record.stopFlag == 0 ? '停用' : '启用' }}
          </a-button>
          <a-button
              v-if="record.isGroup == 0"
              size="small"
              type="text"
              status="danger"
              @click="handleDelete(record)"
          >
            删除
          </a-button>
          <a-button
              v-if="record.isGroup == 0"
              size="small"
              type="text"
              @click="handleToVariable"
          >
            变量
          </a-button>
        </template>
      </a-table>

      <!-- 操作弹框 -->
      <a-modal
          width="450px"
          v-model:visible="operateModalModel.visible"
          class="modal-box"
      >
        <template #title>
          <icon-close-circle v-if="operateModalModel.type == 1" size="18" style="color: rgb(var(--red-6)); margin-right: 5px" />
          <icon-exclamation-circle v-else size="18" style="color: rgb(var(--orange-6)); margin-right: 5px" />
          {{ '确认提示' }}
        </template>
        <div style="text-align: center">是否确认{{ operateModalModel.title }}名称为【{{ operateModalModel.name }}】的数据项？</div>
        <template #footer>
          <div style="text-align: center">
            <a-space>
              <a-button type="primary" status="danger" @click="handleOperateModelCancle">取消</a-button>
              <a-button type="primary" @click="handleOperateModelOk">确认</a-button>
            </a-space>
          </div>
        </template>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { listDevice, listFusionGroup } from '../../apis/device';
import { TableColumnData, TableInstance } from '@arco-design/web-vue';
import useLoading from '../../utils/loading';
import StopFlag from '../../components/stop-flag/index.vue';
import { useRouter } from 'vue-router';

// 加载状态管理
const { loading, setLoading } = useLoading(true);
const router = useRouter();

// 标签页状态
const tabsActiveKey = ref<number>(0);
const tabsList = ref<Array<{ key: string, value: number }>>([]);

// 获取标签页数据
const fetchTabData = async () => {
  try {
    const res = await listDevice();
    if (res.data.code === 200) {
      tabsList.value = res.data.data;
      tabsActiveKey.value = res.data.data[0].value;
      await handleTabsChange();
    }
  } catch (error) {
    console.error('获取标签页数据失败', error);
  }
};

// 表格列配置
const columns = computed<TableColumnData[]>(() => [
  {
    title: '名称',
    dataIndex: 'deviceName',
    slotName: 'deviceName',
    align: 'left',
    fixed: 'left',
    width: 180
  },
  {
    title: '组件容量(kWp)',
    dataIndex: 'ratedVolume',
    slotName: 'ratedVolume',
    align: 'center',
    width: 140
  },
  {
    title: '发电功率(kW)',
    dataIndex: 'deviceDayRuntime.electricPower',
    slotName: 'electricPower',
    align: 'center',
    width: 140
  },
  {
    title: '当日发电量(kWH)',
    dataIndex: 'deviceDayRuntime.electricQuantity',
    slotName: 'electricQuantity',
    align: 'center',
    width: 150
  },
  {
    title: '当日满发电小时',
    dataIndex: 'deviceDayRuntime.electricHours',
    slotName: 'electricHours',
    align: 'center',
    width: 140
  },
  {
    title: '直流离散率',
    dataIndex: 'deviceDayRuntime.dcDispersionRate',
    slotName: 'dcDispersionRate',
    align: 'center',
    width: 110
  },
  {
    title: '功率归一化',
    dataIndex: 'deviceDayRuntime.normalizedRate',
    slotName: 'normalizedRate',
    align: 'center',
    width: 120
  },
  {
    title: '数据更新时间',
    dataIndex: 'deviceDayRuntime.staticTime',
    slotName: 'staticTime',
    align: 'center',
    width: 140
  },
  {
    title: '状态',
    dataIndex: 'stopFlag',
    slotName: 'stopFlag',
    align: 'center',
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 220,
    slotName: 'operate',
    align: 'center',
    fixed: 'right'
  }
]);

// 表格数据
const renderData = ref<Array<any>>([]);
const searchModel = ref({ groupName: '' });
const tableRef = ref<TableInstance>();

// 标签页切换处理
const handleTabsChange = async () => {
  searchModel.value.groupName = tabsList.value.find(
      (item: { value: number }) => item.value === tabsActiveKey.value
  )?.key || '';
  await fetchData();
  tableRef.value?.expandAll(true);
};

// 获取表格数据
const fetchData = async () => {
  setLoading(true);
  try {
    const res = await listFusionGroup(searchModel.value);
    if (res.data.code === 200) {
      renderData.value = res.data.data;
      tableRef.value?.expandAll(true);
    }
  } catch (error) {
    console.error('获取表格数据失败', error);
  } finally {
    setLoading(false);
  }
};

// 操作弹框模型
const generateOperateModalModel = () => ({
  type: 0,         // 0: 状态操作, 1: 删除操作
  visible: false,  // 弹框可见性
  title: '',       // 操作标题
  id: 0,           // 操作数据ID
  value: 0,        // 状态值
  name: ''         // 设备名称
});
const operateModalModel = ref(generateOperateModalModel());

// 停用/启用操作
const handleStopFlag = (record: any) => {
  operateModalModel.value.visible = true;
  operateModalModel.value.id = record.id;
  operateModalModel.value.title = record.stopFlag === 0 ? '停用' : '启用';
  operateModalModel.value.name = record.deviceName;
  operateModalModel.value.value = record.stopFlag === 0 ? 1 : 0;
  operateModalModel.value.type = 0;
};

// 删除操作
const handleDelete = (record: any) => {
  operateModalModel.value.visible = true;
  operateModalModel.value.id = record.id;
  operateModalModel.value.title = '删除';
  operateModalModel.value.name = record.deviceName;
  operateModalModel.value.type = 1;
};

// 取消操作
const handleOperateModelCancle = () => {
  operateModalModel.value = generateOperateModalModel();
};

// 确认操作
const handleOperateModelOk = () => {
  if (operateModalModel.value.type === 0) {
    // 状态更新
    renderData.value.forEach(group => {
      group.children.forEach(item => {
        if (item.id === operateModalModel.value.id) {
          item.stopFlag = operateModalModel.value.value;
        }
      });
    });
  } else if (operateModalModel.value.type === 1) {
    // 删除操作
    renderData.value.forEach(group => {
      const index = group.children.findIndex(item => item.id === operateModalModel.value.id);
      if (index !== -1) {
        group.children.splice(index, 1);
      }
    });
  }
  operateModalModel.value.visible = false;
};

// 跳转到变量列表页面
const handleToVariable = () => {
  router.push({ path: '/Photovoltaicequipment/variablelist' });
};

// 组件挂载时初始化
onMounted(async () => {
  await fetchTabData();
});
</script>

<style scoped>
/* 自定义样式可在此添加 */
.modal-box {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>